#!/usr/bin/env python3
'''
todo 对比01的代码
主干与01相同，但是使用的Q函数的值进行比对

该q值更新主要是先随机玩N局后再更新Q值
'''
import gymnasium as gym
import collections
from tensorboardX import SummaryWriter

ENV_NAME = "FrozenLake-v1"
GAMMA = 0.9
TEST_EPISODES = 20


class Agent:
    def __init__(self):
        self.env = gym.make(ENV_NAME)
        self.state = self.env.reset()
        self.rewards = collections.defaultdict(float)
        self.transits = collections.defaultdict(collections.Counter)
        self.values = collections.defaultdict(float) # key: 当前状态，当前执行的当作 values:到达的所有目标状态的下一个状态中最大的激励反馈值累计 这个就是Q值

    def play_n_random_steps(self, count):
        for _ in range(count):
            action = self.env.action_space.sample()
            new_state, reward, is_done, _ = self.env.step(action)
            self.rewards[(self.state, action, new_state)] = reward
            self.transits[(self.state, action)][new_state] += 1
            self.state = self.env.reset() if is_done else new_state

    def select_action(self, state):
        '''

        从values统计中获取当前状态所能到达的状态中最大激励的动作

        '''

        best_action, best_value = None, None
        for action in range(self.env.action_space.n):
            action_value = self.values[(state, action)]
            if best_value is None or best_value < action_value:
                best_value = action_value
                best_action = action
        return best_action

    def play_episode(self, env):
        total_reward = 0.0
        state = env.reset()
        while True:
            action = self.select_action(state)
            new_state, reward, is_done, _ = env.step(action)
            self.rewards[(state, action, new_state)] = reward
            self.transits[(state, action)][new_state] += 1
            total_reward += reward
            if is_done:
                break
            state = new_state
        return total_reward

    def value_iteration(self):
        # 遍历所有的观察空间，也就是状态
        for state in range(self.env.observation_space.n):
            # 遍历所有的状态空间
            for action in range(self.env.action_space.n):
                action_value = 0.0
                # 获取当前状态+动作所到达的目标状态以及次数
                target_counts = self.transits[(state, action)]
                # 统计总次数
                total = sum(target_counts.values())
                # 遍历所有的目标状态
                for tgt_state, count in target_counts.items():
                    # 获取激励值
                    reward = self.rewards[(state, action, tgt_state)]
                    # 从所到达的目标状态中获取目标状态所能到达的最大激励的动作
                    best_action = self.select_action(tgt_state)
                    # 累计当前的目标状态的动作激励反馈
                    action_value += (count / total) * (reward + GAMMA * self.values[(tgt_state, best_action)])
                # 将当前状态+执行的动作 所能到达的所有目标状态的激励值存储在values中
                self.values[(state, action)] = action_value


if __name__ == "__main__":
    test_env = gym.make(ENV_NAME)
    agent = Agent()
    writer = SummaryWriter(comment="-q-iteration")

    iter_no = 0
    best_reward = 0.0
    while True:
        iter_no += 1
        agent.play_n_random_steps(100)
        agent.value_iteration()

        reward = 0.0
        for _ in range(TEST_EPISODES):
            reward += agent.play_episode(test_env)
        reward /= TEST_EPISODES
        writer.add_scalar("reward", reward, iter_no)
        if reward > best_reward:
            print("Best reward updated %.3f -> %.3f" % (best_reward, reward))
            best_reward = reward
        if reward > 0.80:
            print("Solved in %d iterations!" % iter_no)
            break
    writer.close()
